<?php

class User_orders extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    
    function getDay($mealtime_id){
        $this->db->from("user_orders as UO");
        $this->db->join("users as U", "U.user_id = UO.user_id");
        $this->db->join("mealtime_meals as MTM", "MTM.mealtime_meals_id = UO.mealtime_meals_id");
        $this->db->join("meals as M", "M.meal_id = MTM.meal_id");
        
        $this->db->where("MTM.mealtime_id",  $mealtime_id);
        
        $this->db->order_by("user_title", "asc");
        return $this->db->get();
    }
    
    function order($user_id, $mealtime_meals_id, $comment){
        //Get the mealtime_id
        $this->db->select("mealtime_id");
        $this->db->where("mealtime_meals_id",$mealtime_meals_id);
        $query = $this->db->get("mealtime_meals");
        
        if ($query->num_rows() == 0){
            //there is no mealtime
            return false;
        }
        $mealtime_id = $query->row()->mealtime_id;
                
        
        $this->db->trans_start();
        
        //perform joins
        $this->db->from("user_orders AS UO");
        $this->db->join("mealtime_meals AS MTM", "MTM.mealtime_meals_id = UO.mealtime_meals_id");
        
        //Check if user has already placed an order on current day
        $this->db->where("UO.user_id",$user_id);
        $this->db->where("MTM.mealtime_id",  $mealtime_id);
         
        $this->db->select("UO.user_orders_id");
        
        $query = $this->db->get();
        
        if ($query->num_rows() > 0){
            //If an order exists then we delete it
            $uoid = $query->row()->user_orders_id;
            $this->db->where("user_orders_id", $uoid);
            $this->db->delete("user_orders");
        }
        
        //now to add the new row
        $data['mealtime_meals_id'] = $mealtime_meals_id;
        $data['user_id'] = $user_id;
        if (!empty($comment)) {
            $data['user_order_comment'] = $comment;
        }        
        
        $this->db->insert("user_orders",$data);
        
        $this->db->trans_complete();
        return $this->db->trans_status();
        
    }
    
    
    function deleteOrder($user_id, $mealtime_id){
        
        $this->db->from('mealtime_meals as MTM');
        $this->db->join('user_orders as UO', 'UO.mealtime_meals_id = MTM.mealtime_meals_id');
        
        $this->db->where('mealtime_id', $mealtime_id);
        $this->db->where('user_id', $user_id);
        $this->db->select('user_orders_id');
        
        $user_orders = $this->db->get();
        
        if ($user_orders->num_rows() == 0){
            return false;
        }
                
        $this->db->where('user_orders_id', $user_orders->row()->user_orders_id);
        $this->db->delete('user_orders');
        
        return true;
    }
    
}

